import { applySnapshot, Instance, SnapshotOut, types } from "mobx-state-tree"
import type { Product as IAPProduct } from "react-native-iap"

const createInitialSnapshot = () => ({
  products: [] as IAPProduct[],
  isLoading: false,
  lastUpdatedAt: null as number | null,
})

export const ProductStoreModel = types
  .model("ProductStore", {
    products: types.optional(types.array(types.frozen<IAPProduct>()), []),
    isLoading: types.optional(types.boolean, false),
    lastUpdatedAt: types.maybeNull(types.number),
  })
  .views((self) => ({
    get hasProducts() {
      return self.products.length > 0
    },
    getProductById(productId: string) {
      return self.products.find((item) => item.productId === productId) || null
    },
  }))
  .actions((self) => {
    const reset = () => {
      applySnapshot(self, createInitialSnapshot())
    }

    const setLoading = (value: boolean) => {
      self.isLoading = value
    }

    const setProducts = (items: IAPProduct[]) => {
      self.products.replace(items)
      self.lastUpdatedAt = Date.now()
    }

    return {
      reset,
      setLoading,
      setProducts,
    }
  })

export interface ProductStore extends Instance<typeof ProductStoreModel> {}
export interface ProductStoreSnapshot extends SnapshotOut<typeof ProductStoreModel> {}

export const createProductInitialSnapshot = () => createInitialSnapshot()
